package org.jeecg.modules.demo.mes.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.demo.mes.entity.MesMaterial;
import org.jeecg.modules.demo.mes.entity.MesMaterialDetail;
import org.jeecg.modules.demo.mes.service.IMesMaterialDetailsService;
import org.jeecg.modules.demo.mes.service.IMesMaterialService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 物料表
 * @Author: jeecg-boot
 * @Date: 2022-10-27
 * @Version: V1.0
 */
@Api(tags = "物料表")
@RestController
@RequestMapping("/mes/mesMaterial")
@Slf4j
public class MesMaterialController extends JeecgController<MesMaterial, IMesMaterialService> {
    @Autowired
    private IMesMaterialService mesMaterialService;
    @Autowired
    private IMesMaterialDetailsService mesMaterialDetailsService;

    /**
     * 分页列表查询
     *
     * @param mesMaterial
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "物料表-分页列表查询")
    @ApiOperation(value = "物料表-分页列表查询", notes = "物料表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MesMaterial>> queryPageList(MesMaterial mesMaterial,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<MesMaterial> queryWrapper = QueryGenerator.initQueryWrapper(mesMaterial, req.getParameterMap());
        Page<MesMaterial> page = new Page<MesMaterial>(pageNo, pageSize);
        IPage<MesMaterial> pageList = mesMaterialService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mesMaterial
     * @return
     */
    @AutoLog(value = "物料表-添加")
    @ApiOperation(value = "物料表-添加", notes = "物料表-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_material:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MesMaterial mesMaterial, HttpServletRequest request) {
        //检查物料号是否重复
        checkMesMaterialSequence(mesMaterial);
        mesMaterialService.saveMesMaterial(mesMaterial, JwtUtil.getUserNameByToken(request));
        return Result.OK("添加成功！");
    }

    /**
     * 校验物料号不能重复
     */
    private void checkMesMaterialSequence(MesMaterial mesMaterial) {
        final String materialSequence = mesMaterial.getMaterialSequence();
        final String mesMaterialId = mesMaterial.getId();
        final Map<String, Object> cxMap = new HashMap<>();
        cxMap.put("materialSequence", materialSequence);
        final List<MesMaterial> list = mesMaterialService.queryMesMaterialsSelective(cxMap);
        if (list == null || list.size() == 0) {
            return;
        }
        final String msg = "物料号重复，请修改后再保存";
        if (StringUtils.isBlank(mesMaterialId)) {
            //新增
            throw new JeecgBootException(msg);
        }
        //编辑
        if (list.size() > 1) {
            throw new JeecgBootException(msg);
        }
        final MesMaterial mesMaterialFromDB = list.get(0);
        if (!StringUtils.equals(mesMaterialId, mesMaterialFromDB.getId())) {
            throw new JeecgBootException(msg);
        }
    }

    /**
     * 编辑
     *
     * @param mesMaterial
     * @return
     */
    @AutoLog(value = "物料表-编辑")
    @ApiOperation(value = "物料表-编辑", notes = "物料表-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_material:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MesMaterial mesMaterial) {
        //检查物料号是否重复
        checkMesMaterialSequence(mesMaterial);
        //校验数量是否小于使用数量
        checkMesMaterialQuantity(mesMaterial);
        mesMaterialService.updateMesMaterialById(mesMaterial);
        return Result.OK("编辑成功!");
    }

    /**
     * 校验修改数量
     */
    private void checkMesMaterialQuantity(MesMaterial mesMaterial) {
        final String id = mesMaterial.getId();
        final Map<String, Object> cxMap = new HashMap<>();
        cxMap.put("mainId", id);
        cxMap.put("materialStatus", "2");
        final List<MesMaterialDetail> detailsList = mesMaterialDetailsService.queryMaterialDetailsSelective(cxMap);
        if (detailsList == null) {
            return;
        }
        final int size = detailsList.size();
        if (size > mesMaterial.getMaterialNumber()) {
            throw new JeecgBootException("该物料已经被使用了" + size + "件，数量不能低于" + size + "件");
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "物料表-通过id删除")
    @ApiOperation(value = "物料表-通过id删除", notes = "物料表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_material:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        //校验物料条码是否有被使用
        checkMesMaterialDetailsUsed(id);
        mesMaterialService.removeMesMaterialById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 检查物料条码是否有被使用的
     */
    private void checkMesMaterialDetailsUsed(String id) {
        final Map<String, Object> cxMap = new HashMap<>();
        cxMap.put("mainId", id);
        cxMap.put("materialStatus", "2");
        final List<MesMaterialDetail> details = mesMaterialDetailsService.queryMaterialDetailsSelective(cxMap);
        if (details != null && details.size() > 0) {
            throw new JeecgBootException("该物料已经被使用，请移除使用后再操作");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "物料表-批量删除")
    @ApiOperation(value = "物料表-批量删除", notes = "物料表-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_material:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesMaterialService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "物料表-通过id查询")
    @ApiOperation(value = "物料表-通过id查询", notes = "物料表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MesMaterial> queryById(@RequestParam(name = "id", required = true) String id) {
        MesMaterial mesMaterial = mesMaterialService.getById(id);
        if (mesMaterial == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(mesMaterial);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesMaterial
     */
    //@RequiresPermissions("org.jeecg.modules.demo:mes_material:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesMaterial mesMaterial) {
        return super.exportXls(request, mesMaterial, MesMaterial.class, "物料表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("mes_material:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesMaterial.class);
    }

}
